package net.homeip.dometec.autodownloadfatto;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

import net.homeip.dometec.autodownloadfatto.utils.CLabel;
import net.homeip.dometec.autodownloadfatto.utils.OSValidator;
import net.homeip.dometec.autodownloadfatto.utils.OperUrl;

public class MainWindow extends JFrame {

	private static final long serialVersionUID = 1L;

	public static final NumberFormat nf = new DecimalFormat("00");
	public static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	public static final SimpleDateFormat fds = new SimpleDateFormat("yyyyMMdd");

	public static final Pattern datefile = Pattern.compile("^ilfatto(\\d{4})(\\d{2})(\\d{2}).pdf$");
	public static final String CONFIG_FILE = System.getProperty("user.home") + File.separatorChar + ".ilfattoqt/" + File.separatorChar
			+ "config.properties";

	private static File conf = new File(CONFIG_FILE);
	private JLabel label;
	private CLabel clabel;
	private JProgressBar progressBar;

	public static void main(String[] args) {

		nf.setMinimumIntegerDigits(2);

		if (!conf.isFile()) {
			conf.getParentFile().mkdirs();
			new ConfigWindow(conf, true);
		} else {
			new MainWindow();
		}

	}

	public MainWindow() {

		final File conf = new File(CONFIG_FILE);

		setTitle("Download Automatico Fatto Quotidiano");
		setSize(370, 150);

		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		SpringUtilities.centerWindow(this);

		setLayout(new GridBagLayout());

		// Non penso si possa usare il logo senza permesso

		// try {
		// InputStream resourceAsStream =
		// getClass().getClassLoader().getResourceAsStream(
		// "il-fatto-quotidiano-icon.jpg");
		// setIconImage(ImageIO.read(resourceAsStream));
		// URL resource =
		// getClass().getClassLoader().getResource("il-fatto-quotidiano.jpg");
		// ImageIcon icon = new ImageIcon(resource);
		// JLabel comp = new JLabel(icon);
		// GridBagConstraints c = new GridBagConstraints();
		// c.fill = GridBagConstraints.HORIZONTAL;
		// c.gridwidth = 2;
		// add(comp, c);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }

		label = new JLabel("Autenticazione...");
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(10, 10, 10, 10);
		c.gridwidth = 2;
		c.gridx = 0;
		c.gridy = 1;
		add(label, c);

		progressBar = new JProgressBar(0, 100);
		progressBar.setValue(0);
		progressBar.setStringPainted(true);
		c = new GridBagConstraints();
		c.insets = new Insets(10, 10, 10, 10);
		c.gridx = 0;
		c.gridy = 2;
		add(progressBar, c);

		ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("config.png"), "Opzioni...");
		JButton optBtn = new JButton("Opzioni...", icon);
		optBtn.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				new ConfigWindow(conf);
			}
		});
		c = new GridBagConstraints();
		c.insets = new Insets(10, 10, 10, 10);
		c.gridx = 1;
		c.gridy = 2;
		add(optBtn, c);

		clabel = new CLabel("termini e condizioni");
		clabel.setClickable(true, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				OperUrl.showInBrowser("http://code.google.com/p/autodownload-fattoqt/wiki/TerminiECondizioni", null);
			}
		}, null);
		c = new GridBagConstraints();
		c.insets = new Insets(0, 0, 0, 0);
		c.gridwidth = 2;
		c.gridx = 0;
		c.gridy = 3;
		add(clabel, c);

		pack();
		setVisible(true);

		try {

			Properties prop = new Properties();
			prop.load(new FileInputStream(conf));
			String user = prop.getProperty("user");
			String pass = prop.getProperty("pass");
			String outdir = prop.getProperty("outdir");
			String show = prop.getProperty("show");
			Boolean closeonend = new Boolean(prop.getProperty("closeonend"));
			Date mindate = sdf.parse(prop.getProperty("mindate"));

			Calendar from = getLastDate(outdir, mindate);
			from.add(Calendar.DAY_OF_MONTH, 1);

			Calendar todate = Calendar.getInstance();
			todate.set(Calendar.MILLISECOND, 0);
			todate.set(Calendar.SECOND, 0);
			todate.set(Calendar.MINUTE, 0);
			todate.set(Calendar.HOUR, 0);

			HttpAccess httpAccess = new HttpAccess();
			httpAccess.autentica(user, pass);

			while (!from.after(todate)) {
				label.setText("Recupero pdf del " + sdf.format(from.getTime()));
				this.repaint();
				String filename = httpAccess.recuperaPdf(outdir, from.get(Calendar.YEAR), from.get(Calendar.MONTH) + 1,
						from.get(Calendar.DAY_OF_MONTH), this, progressBar);
				from.add(Calendar.DAY_OF_MONTH, 1);

				if ("all".equals(show) && !from.after(todate)) {
					openPDF(filename);
				}
			}

			showLastEdition(outdir);

			label.setText("Finito.");
			progressBar.setValue(progressBar.getMaximum());
			this.repaint();

			if (closeonend)
				System.exit(0);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void showLastEdition(String outdir) throws IOException {

		Calendar fromdate = Calendar.getInstance();
		fromdate.add(Calendar.MONTH, -1);
		Calendar lastDate = getLastDate(outdir, fromdate.getTime());

		String filename = "ilfatto" + fds.format(lastDate.getTime()) + ".pdf";
		openPDF(outdir + File.separator + filename);

	}

	public void openPDF(String filename) throws IOException {
		if (filename.endsWith(".pdf")) {
			if (OSValidator.isWindows())
				Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + filename);
			else if (OSValidator.isMac())
				Runtime.getRuntime().exec("open " + filename);
			else if (OSValidator.isUnix())
				Runtime.getRuntime().exec(new String[] { "okular", filename });
		}
	}

	public Calendar getLastDate(String outdir, Date fromdate) {
		Calendar mindate = Calendar.getInstance();
		mindate.setTimeInMillis(fromdate.getTime());
		mindate.set(Calendar.MILLISECOND, 0);
		mindate.set(Calendar.SECOND, 0);
		mindate.set(Calendar.MINUTE, 0);
		mindate.set(Calendar.HOUR, 0);

		File dir = new File(outdir);
		File[] listFiles = dir.listFiles();
		for (File file : listFiles) {
			Matcher matcher = datefile.matcher(file.getName());
			if (matcher.find() && matcher.groupCount() == 3) {
				Calendar cFile = Calendar.getInstance();
				cFile.set(Calendar.MILLISECOND, 0);
				cFile.set(Calendar.SECOND, 0);
				cFile.set(Calendar.MINUTE, 0);
				cFile.set(Calendar.HOUR, 0);
				cFile.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(3)));
				cFile.set(Calendar.MONTH, Integer.parseInt(matcher.group(2)) - 1);
				cFile.set(Calendar.YEAR, Integer.parseInt(matcher.group(1)));

				if (mindate.before(cFile))
					mindate = cFile;
			}
		}

		return mindate;
	}

}
